package com.user_hosted_storage.server.bl;

import java.io.File;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;

import com.google.gson.Gson;
import com.user_hosted_storage.entities.Client;
import com.user_hosted_storage.server.dal.ClientFacade;


/**
 * Session Bean implementation class RegistrationTimer
 */
@Stateless
public class RegistrationTimer implements RegistrationTimerRemote {

	private static Logger log = Logger.getLogger(RegistrationTimer.class.getName());

	public static final long MILIS_IN_MINUTE = 60l*1000l;
	public static final long MILIS_IN_HOUR = 60l*MILIS_IN_MINUTE;
	public static final long MILIS_IN_DAY = 24l*MILIS_IN_HOUR;

	private static final String TIMER_ID = "RegistrationTimer";

	private static long lastTimeRan = -1;

	@Resource
	private SessionContext ctx;

	@EJB
	private ClientFacade clientFacade;
	
	@EJB
	private CustomersManagerRemote customersManager;

	
//	@Resource(mappedName="mail_session")
//	private Session mailSession;

	@Timeout
	public void timeout(Timer timer){

		if(((System.currentTimeMillis() - lastTimeRan >= MILIS_IN_MINUTE)) || lastTimeRan ==-1){
			handleRegistrations();
			lastTimeRan = System.currentTimeMillis();
		}

	}

	public void handleRegistrations() {
		System.out.println("Getting jabber unregistered");
		List<Client> jaberUnregistered = clientFacade.getUnregisteredJabber();
		System.out.println(jaberUnregistered.size() + " unregistered");
		

		for (Client client : jaberUnregistered) {
			customersManager.registerJabber(client.getId());
		}

	}

	

//	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
//	private void sendActivationLink(long id) {
//
//		Client client = clientFacade.find(id);
//		
//		log.info("Sending message to "+client.getEmail());
//		
//		try {
//
//			// Instead of simple text, a .html template should be added here!
//			String propDir = System.getProperty("PROP_DIR");
//
//			String fullFilename;
//			String filename = "registrationMailTemplate.html";
//			
//			if("ru".equalsIgnoreCase(client.getLang())){
//				filename = "registrationMailTemplateRU.html";
//			}
//			
//			if (propDir.endsWith(File.separator)) {
//				fullFilename = propDir + filename ;
//			} else {
//				fullFilename = propDir + File.separator + filename;
//			}
//
//			File file = new File(fullFilename);
//			byte[] bytes = new byte[(int) file.length()];
//			FileInputStream in = new FileInputStream(file);
//			in.read(bytes);
//			String messageHtml = new String(bytes,"UTF-8");
//			messageHtml = messageHtml.replaceAll("\\$\\{activationCode\\}", client.getRegistrationActivationCode());
//			messageHtml = messageHtml.replaceAll("\\$\\{email\\}", client.getEmail());
//
//			MailUtils.sendMail(mailSession, messageHtml, "Activate your account on Rushphone", client.getEmail());
//			
//			client.setActivationSent(true);
//
//		} catch (AddressException e) {
//			if(client.getBalance() <= 0){
//				clientManagerBean.removeClient(client.getId());
//			}
//			e.printStackTrace();
//		} catch (MessagingException e) {
//			e.printStackTrace();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	@Override
	public void startTask(){
		stopTask();

		ctx.getTimerService().createTimer(0, MILIS_IN_MINUTE, TIMER_ID);


	}

	@SuppressWarnings("unchecked")
	@Override
	public void stopTask(){
		Collection<Timer> timers = ctx.getTimerService().getTimers();

		for (Timer timer : timers) {

			if(timer.getInfo().equals(TIMER_ID)){
				timer.cancel();
			}

		}

	}

}
